package com.ls.lserp.modules.job.web;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.ls.lserp.common.dynamicsource.DataSourceContextHolder;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.SpringContextHolder;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.dbaccess.Entity.OrderEntity;
import com.ls.lserp.dbaccess.Entity.VenderMeterialEntity;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.job.entity.InventoryMaterialEntity;
import com.ls.lserp.modules.job.entity.MaterialEntity;
import com.ls.lserp.modules.job.entity.MaterialReserverMtmEntity;
import com.ls.lserp.modules.job.service.DesignOptionSyncService;
import com.ls.lserp.modules.job.service.DictSyncService;
import com.ls.lserp.modules.job.service.InventoryMaterialSyncService;
import com.ls.lserp.modules.job.service.MaterialSyncService;
import com.ls.lserp.modules.job.service.OgnizationSyncService;
import com.ls.lserp.modules.job.service.OrderStatusSyncService;
import com.ls.lserp.modules.job.service.UploadFileSyncService;
import com.ls.lserp.modules.job.service.VenderMaterialSyncService;

/**
 * @ClassName : DataBaseSyncJob
 * @Description : ERP与平台数据同步 a_upload_file_p a_dict_p a_designoption_p
 *              i_material_p i_inventory_material_p
 *
 * @author : zhigang.gao
 * @date : 2017年7月6日
 */
public class DataBaseSyncJob extends BaseController {

	// ERP与平台数据同步(uploadfile)
	@Autowired
	private UploadFileSyncService uploadFileSyncService = SpringContextHolder.getBean(UploadFileSyncService.class);

	// ERP与平台数据同步(dict)
	@Autowired
	private DictSyncService dictSyncService = SpringContextHolder.getBean(DictSyncService.class);

	// ERP与平台数据同步(designOption)
	@Autowired
	private DesignOptionSyncService designOptionSyncService = SpringContextHolder.getBean(DesignOptionSyncService.class);
	
	// ERP与平台数据同步(fitProperty)
	//@Autowired
	//private FitPropertySyncService fitPropertySyncService = SpringContextHolder.getBean(FitPropertySyncService.class);

	// ERP与平台数据同步(material)
	@Autowired
	private MaterialSyncService materialSyncService = SpringContextHolder.getBean(MaterialSyncService.class);

	// ERP与平台数据同步(a_ognization_p)
	@Autowired
	private OgnizationSyncService ognizationSyncService = SpringContextHolder.getBean(OgnizationSyncService.class);

	// ERP与平台数据同步(inventorymaterial)
	@Autowired
	private InventoryMaterialSyncService inventoryMaterialSyncService = SpringContextHolder
			.getBean(InventoryMaterialSyncService.class);
	
	// ERP订单状态数据与平台数据同步
	@Autowired
	private OrderStatusSyncService orderStatusSyncService = SpringContextHolder.getBean(OrderStatusSyncService.class);
	
	// ERP与平台数据同步(venderMaterial)
	@Autowired
	private VenderMaterialSyncService venderMaterialSyncService = SpringContextHolder.getBean(VenderMaterialSyncService.class);
	
	/**
	 * ERP与平台数据同步
	 * @throws SQLException
	 * 
	 * @author : X.T.H
	 * @date : 2018年6月20日
	 */
	public void dataBaseSync() throws SQLException {
		
		// 获取开始日期时间
		String nowDateTime = DateUtils.getDateTime();

		logger.info("--------------------" + nowDateTime + "ERP与平台数据同步 [" + this.getClass().getName()
				+ "] 开始------------------------");
		
		// 标准表数据同步方法
		baseDataSync();
		
		// 物料数据同步方法
		materialDataSync();
		
		// 订单状态同步更新方法
		//orderStatusDataSync();
		nowDateTime = DateUtils.getDateTime();
		
		logger.info("--------------------" + nowDateTime + "ERP与平台数据同步 [" + this.getClass().getName()
				+ "] 结束------------------------");
		
	}
	
	/**
	 * @Title : uploadFileSync
	 * @Description : ERP与平台数据同步 a_upload_file_p a_dict_p a_designoption_p
	 *              a_ognization_p
	 * @throws SQLException
	 * @return : void
	 *
	 * @author : zhigang.gao
	 * @date : 2017年7月6日
	 */
	public void baseDataSync() throws SQLException {
		
		// 切换ERP数据库
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);

		// 取得ERP系统 UPLOADFILE 数据
		UploadFile uploadFile = new UploadFile();
		uploadFile.setUploadFileList(uploadFileSyncService.findAllList());

		// 取得ERP系统 DICT 数据
//		Dict dict = new Dict();
//		dict.setDictList(dictSyncService.findAllList(dict));
//
//		// 取得ERP系统 DESIGNOPTION 数据
//		DesignoptionCache designoption = new DesignoptionCache();
//		designoption.setDesignoptionList(designOptionSyncService.findAllList(designoption));
//		
//		// 取得ERP系统 OGNIZATION 数据
//		OgnizationPEntity ognizationPEntity = new OgnizationPEntity();
//		ognizationPEntity.setOgnizationPEntityList(ognizationSyncService.findAllList(ognizationPEntity));
//		
//		// 取得ERP系统 BRAND 数据
//		Brand brand = new Brand();
//		brand.setBrandList(ognizationSyncService.findAllBrandList(brand));
//		
//		// 取得ERP系统 OGNIZATION BRAND 关联数据
//		List<OgnizationBarandEntity> ognizationBarandList = new ArrayList<OgnizationBarandEntity>();
//		ognizationBarandList = ognizationSyncService.findAllOgBrandList(brand);
		
		// 切换MTM数据库
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
		
		// a_upload_file_p数据同步
		logger.info("--------------------" + "ERP与平台数据同步.a_upload_file_p " + "----------开始---------");
		if (uploadFile.getUploadFileList() != null && uploadFile.getUploadFileList().size() > 0) {
			// 同步最新数据到MTM
			uploadFileSyncService.dataSync(uploadFile);
		}
		logger.info("--------------------" + "ERP与平台数据同步.a_upload_file_p " + "----------结束---------");
		
		// a_dict_p数据同步
//		logger.info("--------------------" + "ERP与平台数据同步.a_dict_p " + "----------开始---------");
//		if (dict.getDictList() != null && dict.getDictList().size() > 0) {
//			// 同步最新数据到MTM
//			dictSyncService.dataSync(dict);
//		}
//		logger.info("--------------------" + "ERP与平台数据同步.a_dict_p " + "----------结束---------");
//
//		// a_designoption_p数据同步
//		logger.info("--------------------" + "ERP与平台数据同步.a_designoption_p " + "----------开始---------");
//		if (designoption.getDesignoptionList() != null && designoption.getDesignoptionList().size() > 0) {
//			// 同步最新数据到MTM
//			designOptionSyncService.dataSync(designoption);
//		}
//		logger.info("--------------------" + "ERP与平台数据同步.a_designoption_p " + "----------结束---------");
//
//		// a_ognization_p数据同步
//		logger.info("--------------------" + "ERP与平台数据同步.a_ognization_p " + "----------开始---------");
//		if (ognizationPEntity.getOgnizationPEntityList() != null
//				&& ognizationPEntity.getOgnizationPEntityList().size() > 0) {
//			// 同步最新数据到MTM
//			ognizationSyncService.dataSync(ognizationPEntity);
//		}
//		logger.info("--------------------" + "ERP与平台数据同步.a_ognization_p " + "----------结束---------");
//		
//		// a_brand_p数据同步
//		logger.info("--------------------" + "ERP与平台数据同步.a_brand_p " + "----------开始---------");
//		if (brand.getBrandList() != null && brand.getBrandList().size() > 0) {
//			// 同步最新数据到MTM
//			ognizationSyncService.dataSync(brand);
//		}
//		logger.info("--------------------" + "ERP与平台数据同步.a_brand_p " + "----------结束---------");
//		
//		// a_ognization_brand_r数据同步
//		logger.info("--------------------" + "ERP与平台数据同步.a_ognization_brand_r " + "----------开始---------");
//		if (ognizationBarandList != null && ognizationBarandList.size() > 0) {
//			// 同步最新数据到MTM
//			ognizationSyncService.dataSync(ognizationBarandList);
//		}
		logger.info("--------------------" + "ERP与平台数据同步.a_ognization_brand_r " + "----------结束---------");

		// 最后切换ERP数据库
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);

	}

	/**
	 * @Title : materialDataSync
	 * @Description : ERP与平台数据同步 i_material_p i_inventory_material_p
	 * @throws SQLException
	 * @return : void
	 *
	 * @author : zhigang.gao
	 * @date : 2017年7月10日
	 */
	public void materialDataSync() throws SQLException {

		String strMaterialTypeCD = ResourcesUtil.getConfig("MATERIAL_TYPECD");
		String strDeleteFlag = ResourcesUtil.getConfig("delectFlag_zero");
		List<MaterialEntity> synInsertMaterialList = new ArrayList<MaterialEntity>();
		List<MaterialEntity> synUpdateMaterialList = new ArrayList<MaterialEntity>();
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
		
		// 取得MTM系统i_material_p数据
		MaterialEntity materialEntityMTM = new MaterialEntity();
		materialEntityMTM.setMaterialTypeCd(strMaterialTypeCD);
		 
		List<MaterialEntity> materialListMTM = materialSyncService.findAllList(materialEntityMTM);
		Map<Long,String> map = new HashMap<Long,String>();
		for (MaterialEntity entity : materialListMTM) {
			map.put(entity.getMaterialId(), entity.getMaterialCode());
		}
		
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);

		// 取得ERP系统i_material_p数据
		MaterialEntity materialEntity = new MaterialEntity();
		materialEntity.setMaterialTypeCd(strMaterialTypeCD);
		
		List<MaterialEntity> materialListERP = materialSyncService.findAllList(materialEntity);
		
		
		// 物料数量LIST
		List<InventoryMaterialEntity> inventoryMaterialEntityList = new ArrayList<InventoryMaterialEntity>();
		
		// 物料客户关联LIST
		List<VenderMeterialEntity> venderMeterialEntityList = new ArrayList<VenderMeterialEntity>();
		//
		VenderMeterialEntity venderMeterialEntity = null;
		//
		InventoryMaterialEntity inventoryMaterialEntity = null;
		if (materialListERP != null && materialListERP.size() > 0) {

			// 物料对应的库存数量
			for (int i = 0; i < materialListERP.size(); i++) {
				// 平台中不存在该面料
				if (map.get(materialListERP.get(i).getMaterialId()) == null) {
					//
					synInsertMaterialList.add(materialListERP.get(i));
					
					//
					venderMeterialEntity = new VenderMeterialEntity();
					
					venderMeterialEntity.setMaterialId(materialListERP.get(i).getMaterialId());
					
					venderMeterialEntityList.add(venderMaterialSyncService.selectByMaterialID(venderMeterialEntity));
					//
					inventoryMaterialEntity = new InventoryMaterialEntity();
					
					inventoryMaterialEntity.setMaterialId(materialListERP.get(i).getMaterialId());
					inventoryMaterialEntity.setDeleteFlag(strDeleteFlag);
					
					inventoryMaterialEntityList.add(inventoryMaterialSyncService.selectByMaterialID(inventoryMaterialEntity));
				}else {
					synUpdateMaterialList.add(materialListERP.get(i));
				}
			}
							
			materialEntity.setMaterialEntityList(synInsertMaterialList);
			
			DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
			
			if (materialEntity != null) {
				// 同步最新数据到MTM
				materialSyncService.dataSync(materialEntity,synUpdateMaterialList);
			}
			
			logger.info("--------------------" + "ERP与平台数据同步.i_material_p ");
			
			
			if (venderMeterialEntityList != null && venderMeterialEntityList.size() > 0) {
				venderMeterialEntity = new VenderMeterialEntity();
				venderMeterialEntity.setVenderMeterialEntityList(venderMeterialEntityList);
				
				// 同步最新数据到MTM
				venderMaterialSyncService.dataSync(venderMeterialEntity);
			}
			
			logger.info("--------------------" + "ERP与平台数据同步.i_inventory_material_p ");
				
			//
			if (inventoryMaterialEntityList != null && inventoryMaterialEntityList.size() > 0) {
				inventoryMaterialEntity = new InventoryMaterialEntity();
				inventoryMaterialEntity.setInventoryMaterialEntityList(inventoryMaterialEntityList);
				
				// 同步最新数据到MTM
				inventoryMaterialSyncService.dataSync(inventoryMaterialEntity);
			}
			// 最后切换ERP数据库
			DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);
		}
	}
	
	/**
	 * @Title : materialDataSync
	 * @Description : ERP与平台数据同步 i_material_p i_inventory_material_p
	 * @throws SQLException
	 * @return : void
	 *
	 * @author : zhigang.gao
	 * @date : 2017年7月10日
	 */
	public void inventoryMaterialDataSync() throws SQLException {
		// 获取开始日期时间
		String nowDateTime = DateUtils.getDateTime();
		logger.info("--------------------" + nowDateTime + "ERP与平台【库存】数据同步 [" + this.getClass().getName()
				+ "] 开始------------------------");
		/*// 变动库存数据集
		List<InventoryMaterialEntity> inventoryChangedList = null;
		// 原库存数量
		BigDecimal originalStock = null;
		// 变动库存数量
		BigDecimal changedStock = null;
		// 新库存数量
		BigDecimal newStock = null;
		// 切换MTM数据库
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
		// 获取前一天日期
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		// 获取前一天库存消耗信息
		List<MaterialReserverMtmEntity> materialReserverList = inventoryMaterialSyncService.findAllMaterialReserver(date);
		if (materialReserverList != null && materialReserverList.size() > 0) {
			// 切换ERP数据库
			DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);
			// 将物料耗料数据放入Map集合
			Map<Long,BigDecimal> materialReserverMap = new HashMap<Long,BigDecimal>();
			for (MaterialReserverMtmEntity mReserverEntity : materialReserverList) {
				materialReserverMap.put(mReserverEntity.getMaterialId(), mReserverEntity.getRealityQuantity());
			}
			// 获取ERP全部库存数据
			List<InventoryMaterialEntity> allInventoryMaterialList = inventoryMaterialSyncService.findAllList(new InventoryMaterialEntity());
			if (allInventoryMaterialList != null && allInventoryMaterialList.size() > 0) {
				inventoryChangedList = new ArrayList<InventoryMaterialEntity>();
				for (int i = 0; i < allInventoryMaterialList.size(); i++) {
					// 面料消耗
					changedStock = materialReserverMap.get(allInventoryMaterialList.get(i).getMaterialId());
					if (changedStock != null) {
						// 面料原库存数量
						originalStock = allInventoryMaterialList.get(i).getMaterialQuantity();
						// 计算剩余库存数量
						newStock = originalStock.subtract(changedStock);
						allInventoryMaterialList.get(i).setMaterialQuantity(newStock);
						// 放入变动库存集
						inventoryChangedList.add(allInventoryMaterialList.get(i));
					}
				}
				if (inventoryChangedList != null && inventoryChangedList.size() > 0) {
					// 更新变动库存数据
					inventoryMaterialSyncService.updateList(inventoryChangedList);
					System.out.println("/------- 变化库存 面料数量："+inventoryChangedList.size()+" ---------/");
				}
				// 切换MTM数据库
				DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
				// 同步库存
				inventoryMaterialSyncService.updateList(allInventoryMaterialList);
			}
		}*/
		
		
		// 获取ERP全部库存数据
		List<InventoryMaterialEntity> allInventoryMaterialList = inventoryMaterialSyncService.findAllList(new InventoryMaterialEntity());
		// 切换MTM数据库
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
		if (allInventoryMaterialList != null && allInventoryMaterialList.size() > 0) {
			// 同步库存
			inventoryMaterialSyncService.updateList(allInventoryMaterialList);
		}
		// 获取库存预消耗信息
		List<MaterialReserverMtmEntity> materialReserverList = inventoryMaterialSyncService.findAllMaterialReserver();
		if (materialReserverList != null && materialReserverList.size() >0) {
			// 切换ERP数据库
			DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);
			//
			materialReserverList = inventoryMaterialSyncService.setProductionFlag(materialReserverList);
			// 切换MTM数据库
			DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
			//
			inventoryMaterialSyncService.updateProductionFlag(materialReserverList);
		}
		// 最后切换ERP数据库
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);
		nowDateTime = DateUtils.getDateTime();
		logger.info("--------------------" + nowDateTime + "ERP与平台【库存】数据同步 [" + this.getClass().getName()
				+ "] 结束------------------------");
	}

	/**
	 * @Title : orderStatusDataSync
	 * @Description : ERP订单状态与平台数据同步
	 * @throws SQLException
	 * @return : void
	 *
	 * @author : X.T.H
	 * @date : 2018年6月20日
	 */
	public void orderStatusDataSync() throws SQLException {
		
		/*// 切换MTM数据库，获取全部生产中订单数据
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
		// MTM订单集合
		List<OrderEntity> orderEntityListMTM = new ArrayList<OrderEntity>();
		// 获取生产中订单数据
		orderEntityListMTM = orderStatusSyncService.findOrderList(orderEntity);*/
		
		// 订单实体
		OrderEntity orderEntity = new OrderEntity();
		// 切换ERP数据
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);
		// ERP订单集
		List<OrderEntity> orderEntityListERP = new ArrayList<OrderEntity>();
		// 获取全部ERP平台订单订单状态为生产完成和已发货
		orderEntityListERP = orderStatusSyncService.findOrderListERP(orderEntity);
		
		if (orderEntityListERP != null && orderEntityListERP.size() > 0) {
			// 切换MTM数据库，更新订单状态
			DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_MTMSQL);
			
			logger.info("--------------------" + "ERP订单状态与平台数据同步" + "----------开始---------");
			// 同步订单状态
			orderStatusSyncService.updateOrderStatus(orderEntityListERP);
			logger.info("--------------------" + "ERP订单状态与平台数据同步 " + "----------结束---------");
		}
		// 最后切换ERP数据库
		DataSourceContextHolder.setDbType(DataSourceContextHolder.DATA_SOURCE_ZYSQL);
	}
}
